package ua.khuta.myskidka;


import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class FragmentCategoriesList extends Fragment {
	View v;
	ListView lvDiscountsList;
	Database db;
	SimpleCursorAdapter scAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fragment_discounts_catalog, null);
		lvDiscountsList = (ListView) v.findViewById(R.id.lv_discount_list);
		db = Database.getInstance(getActivity());
		Cursor c = db.getCategoriesFromDb();
		String[] from = { Database.CATEGORY_IMAGE, Database.CATEGORY_TITLE, Database.CATEGORY_ITEM_AMOUNT };
		int[] to = { R.id.iv_item_discount_list, R.id.tv_item_discount_list, R.id.tv_item_discount_list_object_count, };
		scAdapter = new SimpleCursorAdapter(getActivity(),
				R.layout.item_discount_list, c, from, to);
		lvDiscountsList.setAdapter(scAdapter);
		lvDiscountsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				Cursor c;
				c = db.getCategoryIdByPosition(position + 1);
				c.moveToFirst();
				int categoryId = c.getInt(0);
				Bundle pos = new Bundle();
				Log.d("myLogs", "category to click" + categoryId);
			
				pos.putInt("categoryId", categoryId);
				
				Fragment fragment = new FragmentSubcategoryList();
				fragment.setArguments(pos);
				FragmentTransaction transaction = getFragmentManager()
						.beginTransaction();
				transaction.replace(R.id.content_frame, fragment);
				transaction.addToBackStack(null);
				transaction.commit();

			}
		});
		return v;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

}
